//
//  ZQNetWorkManager+Extension.swift
//  Timor微博
//
//  Created by 周周旗 on 2019/3/19.
//  Copyright © 2019 ZQ. All rights reserved.
//

import Foundation


// MARK: - 封装新浪微博网络请求的方法
extension ZQNetWorkManager{
    
    /// 加载微博字典数据
    /// - Parameters:
    ///   - since_id: 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 【list微博字典数组/是否成功】
    
    
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion:@escaping (_ list: [[String: AnyObject]]?, _ isSuccess: Bool)->()){
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameters = ["since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        ZQNetWorkManager.shared.tokenRequest(URLString: url, parameters: parameters as [String : AnyObject]) { (json, isSuccess) in
            //从json中获取statusList字典数组
            let result = json?["statuses"] as? [[String: AnyObject]]
            completion(result, isSuccess)
        }
    }
}
// MARK: - Autho 获取授权
extension ZQNetWorkManager{
    
    /// 加载 AccessToken
    ///
    /// - Parameter code: code
    func loadAccessToken(code:String) {
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":WBAPPKey,
                      "client_secret":WBAPPSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WBRedirectURI]
        request(method: .POST, URLString: url, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            
            self.userAccount.yy_modelSet(withJSON: json ?? [:])
            print(self.userAccount )

        }
        
/**
         iOS的存储方式：
         1.偏好设置（小）
         2.沙盒（归档/plist/json/）
         3.数据库（FMDB/CoreData）
         4.钥匙串访问（保存密码 keychain）
 */
        func saveAccount() {
            // 1. 模型转字典
            var dict = self.yy_modelToJSONObject() as? [String : Any] ?? [:]
            
            //需要删除expires_in值 （因此值变化，无需储存）
            dict.removeValue(forKey: "expires_in")
            
            // 2. 字典序列化data
            guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),let filePath = ("useraccount.json" as NSString).cz_appendDocumentDir()
            else {
                return
            }

            // 3. 写入磁盘
            (data as NSData).write(toFile: filePath, atomically: true)
            print("用户保存成功\(filePath)")

        }
    }
}

